<template>
  <view class="map-page">
    <view class="map-card">
      <view class="card-header">
        <text class="card-title">{{ titleText }}</text>
      </view>
      <view class="card-content">
        <LeafletMap
          ref="leafletMapRef"
          map-id="station-map-page"
          :center="[centerLat, centerLng]"
          :zoom="8"
          :show-annotation="true"
          :auto-init="true"
          @map-ready="onMapReady"
        />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import LeafletMap from '@/components/LeafletMap.vue'
import { API_BASE_URL } from '@/config/api.js'
// #ifdef H5
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
// #endif

const leafletMapRef = ref(null)
let map = null
const titleText = ref('')
const centerLat = ref(41.8)
const centerLng = ref(123.4)
const stcd = ref('')

const basinGeometry = ref(null)
const outletPoint = ref(null)
let basinLayer = null
let outletLayer = null

onMounted(async () => {
  const pages = getCurrentPages()
  const current = pages[pages.length - 1]
  const options = current?.options || {}
  stcd.value = options.stcd || ''
  titleText.value = options.stnm || ''
  if (options.lat) centerLat.value = Number(options.lat)
  if (options.lon) centerLng.value = Number(options.lon)
  // 流域面查询
  await fetchBasinGeometry()
})

function onMapReady(m) {
  map = m
  // #ifdef H5
  if (basinGeometry.value) {
    addBasinLayer()
    addOutletLayer()
    setTimeout(() => { map && map.invalidateSize() }, 100)
    return
  }
  try {
    const marker = L.marker([centerLat.value, centerLng.value])
    marker.addTo(map)
    map.setView([centerLat.value, centerLng.value], 15)
  } catch {}
  // #endif
}

async function fetchBasinGeometry() {
  try {
    const response = await uni.request({
      url: `${API_BASE_URL}/api/get_reservoir_by_stcd?basin=${stcd.value}`,
      method: 'GET'
    })
    if (response.data?.success) {
      const data = response.data.data || {}
      basinGeometry.value = data.geometry_geojson || null
      outletPoint.value = {
        lon: data.outlet_coordinates?.longitude,
        lat: data.outlet_coordinates?.latitude,
        name: data.stnm
      }
      if (map && basinGeometry.value) {
        addBasinLayer()
        addOutletLayer()
        setTimeout(() => { map && map.invalidateSize() }, 100)
      }
    }
  } catch {}
}

function addBasinLayer() {
  // #ifdef H5
  if (!map || !basinGeometry.value) return
  if (basinLayer) {
    map.removeLayer(basinLayer)
    basinLayer = null
  }
  basinLayer = L.geoJSON(basinGeometry.value, {
    style: { color: '#ff6600', weight: 3, fillOpacity: 0, opacity: 1 }
  }).addTo(map)
  map.fitBounds(basinLayer.getBounds())
  // #endif
}

function addOutletLayer() {
  // #ifdef H5
  if (!map || !outletPoint.value) return
  if (outletLayer) {
    map.removeLayer(outletLayer)
    outletLayer = null
  }
  const { lon, lat, name } = outletPoint.value
  const outletMarker = L.circleMarker([lat, lon], {
    radius: 6,
    fillColor: '#ff0000',
    color: '#ff0000',
    weight: 2,
    opacity: 1,
    fillOpacity: 0.8
  })
  outletMarker.bindPopup(`<strong>流域出口</strong><br>名称: ${name}<br>坐标: ${lon}°, ${lat}°`)
  outletLayer = L.layerGroup([outletMarker]).addTo(map)
  // #endif
}
</script>

<style scoped>
.map-page { min-height: 90vh; background: #f5f7fa; }
.map-card { background: #ffffff; margin: 0; border-radius: 0; height: 90vh; display: flex; flex-direction: column; }
.card-header { display: flex; justify-content: space-between; align-items: baseline; padding: 16rpx; border-bottom: 1rpx solid #f0f0f0; }
.card-title { font-size: 28rpx; font-weight: 600; color: #2c3e50; }
.card-content { padding: 0; flex: 1; }
.map-card :deep(.leaflet-map) { min-height: 100%; }
</style>
